import base64
import json
import requests
import os
import uuid

def gen_audio_by_bytedance(text, output_file):
    appid = "8694880241"
    access_token= "phMLsOxGntkuYUGmbQ_x4IGPdjqU8uX7"
    cluster = "volcano_tts"

    voice_type = "BV002_streaming" # 通用男声
    # voice_type = "BV504_streaming"  # 美式英语 男
    # voice_type = "BV503_streaming"  # 美式英语 女
    host = "openspeech.bytedance.com"
    api_url = f"https://{host}/api/v1/tts"

    header = {"Authorization": f"Bearer;{access_token}"}

    request_json = {
        "app": {
            "appid": appid,
            "token": access_token,
            "cluster": cluster
        },
        "user": {
            "uid": "2103587455"
        },
        "audio": {
			"voice_type": voice_type,
            "encoding": "mp3",
            "speed_ratio": 1.0,
            "volume_ratio": 1.0,
            "pitch_ratio": 1.0,
        },
        "request": {
            "reqid": str(uuid.uuid4()),
            "text": text,
            "text_type": "plain",
            "operation": "query",
            "with_frontend": 1,
            "frontend_type": "unitTson"
        }
    }
    resp = requests.post(api_url, json.dumps(request_json), headers=header)
    print(f"resp body: \n{resp.json()}")
    if "data" in resp.json():
        data = resp.json()["data"]
        file_to_save = open(output_file, "wb")
        file_to_save.write(base64.b64decode(data))